package com.wulis.seckill.business.controller;

import com.wulis.seckill.aop.RedisLimiter;
import com.wulis.seckill.common.wrapper.ResponseData;
import com.wulis.seckill.common.wrapper.ResponseDataUtil;
import com.wulis.seckill.business.service.SeckillGoodsInfoService;
import com.wulis.seckill.enums.SecKillInventoryEnum;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/seckillgoods")
@Api(tags = "商品秒杀")
@AllArgsConstructor
public class SeckillGoodsInfoController {

    private final SeckillGoodsInfoService seckillGoodsInfoService;

    /**
     * 缓存秒杀数据到redis
     *
     * @return
     */
    @PostMapping(value = "/cachestock")
    public ResponseData saveStock() {
        seckillGoodsInfoService.cacheStock();
        return ResponseDataUtil.buildSuccess();
    }

    /**
     * 获取秒杀缓存redis数据
     *
     * @param goodsId
     * @return
     */
    @PostMapping(value = "/getStock")
    public ResponseData getStock(Long goodsId) {
        return ResponseDataUtil.buildSuccess(seckillGoodsInfoService.getCacheStock(goodsId));
    }

    /**
     * 秒杀商品
     * RedisLimiter注解实现限流器注解
     *
     * @param goodsId
     * @param num
     * @return
     */
    @PostMapping(value = "/lightningdeals")
    @RedisLimiter(name = "seckillgoods_lightningdeals", count = 40, period = 1)
    public ResponseData lightningDeals(Long goodsId, int num) {
        SecKillInventoryEnum secKillSuccess =
                SecKillInventoryEnum.getSecKillSuccess(seckillGoodsInfoService.lightningDeals(goodsId, num));
        return ResponseDataUtil.buildSuccess(secKillSuccess.code(), secKillSuccess.desc());
    }
}
